﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESQWinform;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;

namespace MesProjectWinform.BasicData.基础实现.gongwei
{
    /// <summary>
    /// 工位管理窗体类
    /// </summary>
    public partial class gongwei : DevExpress.XtraEditors.XtraForm
    {
        // 添加字段跟踪当前页码和页大小
        private int currentPageIndex = 1;
        private int currentPageSize = 3;
        private string workstationcode = "";
        private string workstationname = "";
        // 添加总记录数字段
        private int totalRecords = 0;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public gongwei()
        {
            InitializeComponent();
        }
        
        /// <summary>
        /// 查询工位数据
        /// </summary>
        public async void Qry()
        {
            try
            {
                // 构建查询参数
                string url = "api/WorkstationManag/GetWorkstation";
                bool hasParam = false;
                
                // 添加workstationcode参数
                if (!string.IsNullOrEmpty(workstationcode))
                {
                    url += $"?workstationcode={workstationcode}";
                    hasParam = true;
                }
                
                // 添加workstationname参数
                if (!string.IsNullOrEmpty(workstationname))
                {
                    if (hasParam)
                    {
                        url += $"&workstationname={workstationname}";
                    }
                    else
                    {
                        url += $"?workstationname={workstationname}";
                        hasParam = true;
                    }
                }
                
                // 添加分页参数
                if (hasParam)
                {
                    url += $"&pageindex={currentPageIndex}&pagesize={currentPageSize}";
                }
                else
                {
                    url += $"?pageindex={currentPageIndex}&pagesize={currentPageSize}";
                }
                
                // 调用API
                string json = await APIClientl.CallApiAsync(url);
                
                // 使用动态类型解析JSON
                dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
                
                // 将动态数据转换为DataTable
                DataTable dt = new DataTable();
                dt.Columns.Add("Id", typeof(long));
                dt.Columns.Add("Workstationcode", typeof(string));
                dt.Columns.Add("Workstationname", typeof(string));
                dt.Columns.Add("Productionid", typeof(string));
                dt.Columns.Add("Productionlinename", typeof(string));
                dt.Columns.Add("Processid", typeof(string));
                dt.Columns.Add("Workstationdescription", typeof(string));
                dt.Columns.Add("Workstationattributes", typeof(string));
                dt.Columns.Add("Workstationuserid", typeof(string));
                dt.Columns.Add("IsDeleted", typeof(bool));
                dt.Columns.Add("CreatedBy", typeof(string));
                dt.Columns.Add("CreatedTime", typeof(DateTime));
                dt.Columns.Add("UpdatedBy", typeof(string));
                dt.Columns.Add("UpdatedTime", typeof(DateTime));
                
                // 计算数据项数量
                int dataCount = 0;
                
                // 检查Data是否为数组
                if (result.Data is Newtonsoft.Json.Linq.JArray)
                {
                    // 如果是数组，遍历每个元素
                    foreach (var item in result.Data)
                    {
                        AddDataRowToTable(dt, item);
                        dataCount++;
                    }
                }
                else if (result.Data != null)
                {
                    // 如果不是数组但不为空，添加单个对象
                    AddDataRowToTable(dt, result.Data);
                    dataCount = 1;
                }
                
                // 设置数据源
                gridControl1.DataSource = dt;

                // 获取总记录数
                totalRecords = result.TotalCount ?? dataCount;
                
                // 更新分页按钮状态
                UpdatePageButtonStatus(dataCount);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                gridControl1.DataSource = null;
                totalRecords = 0;
                UpdatePageButtonStatus(0);
            }
        }
        
        /// <summary>
        /// 辅助方法：将动态数据添加到DataTable
        /// </summary>
        /// <param name="dt">要添加数据的DataTable</param>
        /// <param name="item">包含数据的动态对象</param>
        private void AddDataRowToTable(DataTable dt, dynamic item)
        {
            DataRow row = dt.NewRow();
            
            // 使用TryGetValue方式安全地获取属性值
            row["Id"] = GetDynamicValue(item, "Id", 0L);
            row["Workstationcode"] = GetDynamicValue(item, "Workstationcode", string.Empty);
            row["Workstationname"] = GetDynamicValue(item, "Workstationname", string.Empty);
            row["Productionid"] = GetDynamicValue(item, "Productionid", string.Empty);
            row["Productionlinename"] = GetDynamicValue(item, "Productionlinename", string.Empty);
            row["Processid"] = GetDynamicValue(item, "Processid", string.Empty);
            row["Workstationdescription"] = GetDynamicValue(item, "Workstationdescription", string.Empty);
            row["Workstationattributes"] = GetDynamicValue(item, "Workstationattributes", DBNull.Value);
            row["Workstationuserid"] = GetDynamicValue(item, "Workstationuserid", DBNull.Value);
            row["IsDeleted"] = GetDynamicValue(item, "IsDeleted", false);
            row["CreatedBy"] = GetDynamicValue(item, "CreatedBy", DBNull.Value);
            row["CreatedTime"] = GetDynamicValue(item, "CreatedTime", DateTime.Now);
            row["UpdatedBy"] = GetDynamicValue(item, "UpdatedBy", DBNull.Value);
            row["UpdatedTime"] = GetDynamicValue(item, "UpdatedTime", DateTime.Now);
            
            dt.Rows.Add(row);
        }
        
        /// <summary>
        /// 辅助方法：安全获取动态对象的属性值
        /// </summary>
        /// <typeparam name="T">属性值类型</typeparam>
        /// <param name="obj">动态对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>属性值或默认值</returns>
        private T GetDynamicValue<T>(dynamic obj, string propertyName, T defaultValue)
        {
            try
            {
                // 检查是否为JObject类型
                if (obj is Newtonsoft.Json.Linq.JObject jObject)
                {
                    if (jObject.ContainsKey(propertyName))
                    {
                        return jObject[propertyName].ToObject<T>();
                    }
                    return defaultValue;
                }
                
                // 尝试通过反射获取属性值
                var value = obj.GetType().GetProperty(propertyName)?.GetValue(obj, null);
                if (value == null)
                    return defaultValue;
                
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                return defaultValue;
            }
        }
        
        /// <summary>
        /// 更新分页按钮状态
        /// </summary>
        /// <param name="currentDataCount">当前数据条数</param>
        private void UpdatePageButtonStatus(int currentDataCount)
        {
            // 上一页按钮：当前页大于1时启用
            button1.Enabled = currentPageIndex > 1;
            
            // 下一页按钮：根据总记录数和当前页码判断是否有下一页
            int totalPages = (int)Math.Ceiling((double)totalRecords / currentPageSize);
            button2.Enabled = currentPageIndex < totalPages;
            
            // 不再在标题中显示分页信息
            // this.Text = $"工位管理 - 第{currentPageIndex}页/共{totalPages}页 (每页{currentPageSize}条，共{totalRecords}条记录)";
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void gongwei_Load(object sender, EventArgs e)
        {
            // 页面加载时显示所有数据
            Qry();
        }
        
        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询参数
                workstationcode = textEdit1.Text.Trim(); // 工位编码
                workstationname = textEdit2.Text.Trim(); // 工位名称
                
                // 重置页码为1（新查询从第一页开始）
                currentPageIndex = 1;
                
                // 调用Qry方法进行查询
                Qry();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 确保页码大于1
            if (currentPageIndex > 1)
            {
                currentPageIndex--;
                Qry();
            }
        }

        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void button2_Click(object sender, EventArgs e)
        {
            // 计算总页数
            int totalPages = (int)Math.Ceiling((double)totalRecords / currentPageSize);
            
            // 确保不超过总页数
            if (currentPageIndex < totalPages)
            {
                currentPageIndex++;
                Qry();
            }
        }
        /// <summary>
        /// 修改工位按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.GetSelectedRows().Length > 0)
                {
                    int rowHandle = view.GetSelectedRows()[0];
                    long id = Convert.ToInt64(view.GetRowCellValue(rowHandle, "Id"));
                    
                    // 调用删除API，使用PUT方法
                    string url = $"api/WorkstationManag/DeleteWorkstation?id={id}";
                    await APIClientl.CallApiAsync(url, "PUT");
                    
                    // 显示删除成功消息
                    XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 刷新数据
                    Qry();
                }
                else
                {
                    XtraMessageBox.Show("请先选择要删除的工位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 删除工位按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.GetSelectedRows().Length > 0)
                {
                    int rowHandle = view.GetSelectedRows()[0];
                    long id = Convert.ToInt64(view.GetRowCellValue(rowHandle, "Id"));
                    
                    // 创建修改页面并传递ID
                    gongup gongup = new gongup(id);
                    
                    // 使用ShowDialog方法并检查返回结果
                    if (gongup.ShowDialog() == DialogResult.OK)
                    {
                        // 如果对话框返回OK（表示修改成功），则刷新数据
                        Qry();
                    }
                }
                else
                {
                    XtraMessageBox.Show("请先选择要修改的工位", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"跳转修改页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 添加工位按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void button4_Click(object sender, EventArgs e)
        {
            gongadd gongadd = new gongadd();
            gongadd.ShowDialog();
        }
    }
}